//
//  PageTitleItem.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/17.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit
import RxSwift


final class PageTitleItem: UIView {
    
    let title: String
    let style: PageTitleStyle
    let index: Int
    
    private lazy var cover: CAShapeLayer = {
        let layer = CAShapeLayer()
        layer.fillColor = style.coverView.color.cgColor
        layer.isHidden = true
        return layer
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = title
        label.font = style.item.font
        label.textColor = style.item.normalColor
        label.textAlignment = .center
        label.sizeToFit()
        return label
    }()
    
    var isSelected = false {
        willSet {
            if newValue == isSelected { return }
            itemSelectDidChange(newValue)
        }
    }
    
    let didTapSubject = PublishSubject<PageTitleItem>()
    
    init(title: String, style: PageTitleStyle, index: Int) {
        self.title = title
        self.style = style
        self.index = index
        super.init(frame: .zero)
        setupSubviews()
        sutupGesture()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if style.coverView.isShow {
            cover.path = UIBezierPath(roundedRect: bounds, cornerRadius: style.coverView.radius).cgPath
        }
    }
}

private extension PageTitleItem {
    func setupSubviews() {
        size = CGSize(width: titleLabel.size.width + style.coverView.maigin, height: titleLabel.size.height + style.coverView.maigin)
        if style.coverView.isShow {
            layer.addSublayer(cover)
        }
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
    }
    
    func sutupGesture() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(PageTitleItem.itemDidTap))
        addGestureRecognizer(tap)
    }
    
    func itemSelectDidChange(_ isSelected: Bool) {
        if isSelected {
            if style.scale.isShow {
                transform = CGAffineTransform(scaleX: style.scale.value, y: style.scale.value)
            }
            if style.coverView.isShow {
                cover.isHidden = false
                titleLabel.textColor = style.item.selectedColor
            }
        } else {
            if style.scale.isShow {
                transform = .identity
            }
            if style.coverView.isShow {
                cover.isHidden = true
                titleLabel.textColor = style.item.normalColor
            }
        }
    }
}

@objc private extension PageTitleItem {
    func itemDidTap() {
        didTapSubject.onNext(self)
    }
}
